package shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author lzh
 * @description
 * @date 2021/2/12
 */
public class JwtRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return null != token && token instanceof JwtToken;
    }

    /**
     * 用户认证，在此处给登录用户授予角色
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String tokenString = (String) principalCollection.getPrimaryPrincipal();
        CurrentUser user = JwtUtil.get(tokenString);
        int roleId = user.getRoleId();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if (roleId == 1) {
            simpleAuthorizationInfo.addRole("admin");
        }else if (roleId == 2) {
            simpleAuthorizationInfo.addRole("teacher");
        }else if (roleId == 3) {
            simpleAuthorizationInfo.addRole("student");
        }
        return simpleAuthorizationInfo;
    }

    /**
     * 用户认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        String token = (String) authenticationToken.getCredentials();
        CurrentUser user = JwtUtil.get(token);
        if (user == null) {
            throw new AuthenticationException("token非法或者token已失效");
        }


        return new SimpleAuthenticationInfo(token, token, "jwt_realm");
    }
}
